<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>

    <div class="add">
      <div class="common-layout">
        <el-container>
          <el-main>
            <el-row>
              <el-col :span="24">
                <div class="grid-content ep-bg-purple">
                  <h4>基本信息</h4>
                  <el-form :inline="true" :model="salesOrders" :rules="rules" status-icon ref="formRef">
                    <el-form-item label="单据编号" prop="docCode">
                <el-input
                    v-model="salesOrders.docCode"
                    style="width: 240px"
                    placeholder="请输入单据编号"
                    clearable
                    :disabled="true"
                    />
                        </el-form-item>
                    <!-- 客户 -->
                    <el-form-item label="客户" prop="cid">
                            <el-select
                              v-model="salesOrders.cid"
                              placeholder="请选择客户"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="customer in customerList"
                                :key="customer.id"
                                :label="`${customer.code} - ${customer.name}`"
                                :value="customer.id"
                              />
                            </el-select>
                          </el-form-item>

                    <!-- 报价日期 -->
                    <el-form-item label="单据日期" prop="docDate">
                      <el-date-picker
                        v-model="salesOrders.docDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                      />
                    </el-form-item>
                    <!-- 业务员 -->
                    <el-form-item label="业务员" prop="uuid">
                            <el-select
                              v-model="salesOrders.uid"
                              placeholder="请选择业务员"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="user in userList"
                                :key="user.id"
                                :label="user.name"
                                :value="user.id"
                              />
                            </el-select>
                          </el-form-item>

                    <!-- 部门 -->
                    <el-form-item label="部门" prop="did">
                      <el-select
                        v-model="salesOrders.did"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                      >
                        <el-option
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                        />
                      </el-select>
                    </el-form-item>
                      <el-form-item label="单据备注" prop="notes">
                           <el-input v-model="salesOrders.notes" style="width: 240px"
                             placeholder="请输入单据备注" />
                       </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </div>
    </div>
    <div>
      <div class="toolbar">
    <el-button type="primary">商品信息</el-button>
    <el-button @click="addGoodsRow">继续添加</el-button>
    <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
    </div>

  <!-- 商品信息表格 -->
    <div class="goods-table-container">
  <el-table :data="tableData" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
    <el-table-column type="selection" width="55" />
    <!-- 商品编码（带必填标识的下拉框） -->
    <el-table-column label="商品编码" width="150">
      <template #header>
        <span class="required-label">商品编码</span>
      </template>
      <template #default="scope">
        <el-select
          v-model="scope.row.code"
          placeholder="请选择商品"
          @change="handleGoodsChange(scope.row)"
          clearable
        >
          <el-option
            v-for="item in goodsList"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </template>
    </el-table-column>

    <!-- 商品名称 -->
    <el-table-column label="商品名称" width="180">
      <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
    </el-table-column>

    <!-- 仓库信息 -->
    <el-table-column label="仓库" width="120" align="center">
      <template #default="scope">{{ scope.row.warehouse || '主仓库' }}</template>
    </el-table-column>

    <!-- 即时库存 -->
    <el-table-column label="即时库存" width="100" align="center">
      <template #default="scope">{{ scope.row.stock || 0 }}</template>
    </el-table-column>

    <!-- 单位（带必填标识） -->
    <el-table-column label="单位" width="80" align="center">
      <template #header>
        <span class="required-label">单位</span>
      </template>
      <template #default="scope">{{ scope.row.unit || '件' }}</template>
    </el-table-column>

    
    
                    <el-table-column label="数量" width="120" align="center">
                        <template #header>
                            <span class="required-label">数量</span>
                        </template>
                        <template #default="scope">
                            <el-input-number 
                                v-model="scope.row.quantity" 
                                :min="1" 
                                controls-position="right"
                                style="width: 100px"
                                @change="calculateTaxPrice(scope.row)"> <!-- 新增事件绑定 -->
                            </el-input-number>
                        </template>
                    </el-table-column>

                    <!-- 实际报价（可输入） -->
                    <el-table-column label="实际报价" width="130" align="center">
                        <template #default="scope">
                            <el-input-number 
                                v-model="scope.row.actualPrice" 
                                :min="1" 
                                :precision="2"
                                controls-position="right" 
                                style="width: 100px"
                                @change="calculateTaxPrice(scope.row)"> <!-- 新增事件绑定 -->
                            </el-input-number>
                        </template>
                    </el-table-column>

                    <el-table-column label="税额" width="120" align="center">
                        <template #default="scope">
                            {{ scope.row.taxAmount?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="价税合计" width="130" align="center">
                        <template #default="scope">
                            {{ scope.row.taxTotal?.toFixed(2) || '0.00' }}
                        </template>
                    </el-table-column>
  

    <!-- 其他只读列 -->
    <el-table-column
      v-for="col in readonlyColumns"
      :key="col.prop"
      :prop="col.prop"
      :label="col.label"
      :width="col.width"
      align="center"
    />
      </el-table>
    </div>
     </div>
     <div class="total-summary">
      <div class="total-label">合计</div>
      <div class="total-amount">{{ formatTotal }}</div>
    </div>
    
  <el-dialog
  v-model="dialogVisible"
  title="销售报价单"
  width="80%"
  top="5vh"
>
  <!-- 查询条件区域 -->
  <div class="dialog-header">
    <el-input
      v-model="searchForm.docCode"
      placeholder="请输入单据编号"
      style="width: 240px;margin-right: 15px"
    />
    <span class="date-label">单据日期：</span>
    <el-date-picker
      v-model="searchForm.startDate"
      type="date"
      placeholder="开始日期"
      value-format="YYYY-MM-DD"
      style="width: 160px"
    />
    <span class="date-separator">~</span>
    <el-date-picker
      v-model="searchForm.endDate"
      type="date"
      placeholder="结束日期"
      value-format="YYYY-MM-DD"
      style="width: 160px;margin-right: 15px"
    />
    <el-button type="primary" icon="Search" @click="searchSalesQuotes">查询</el-button>
    <el-button icon="Refresh" @click="resetSearch">重置</el-button>
    <el-button icon="ArrowDown">展开</el-button>
  </div>

  <!-- 选择状态提示 -->
  <div class="selected-info">
    <span>已选择{{ selectedCount }}项</span>
    <el-button link type="primary" @click="clearSelection">清空</el-button>
  </div>

  <!-- 表格区域 -->
  <el-table
    :data="salesQuotesList"
    border
    height="60vh"
    @selection-change="handleSelectionChange"

  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="doCode" label="单据编号" width="180" />
    <el-table-column prop="bjDate" label="单据日期" width="120" />
    <el-table-column prop="bjName" label="单据主题" width="200" />
    <el-table-column prop="cidStr" label="客户" width="120" />
    <el-table-column prop="didStr" label="业务部门" width="120" />
    <el-table-column prop="uidStr" label="业务员" width="120" />
   <el-table-column prop="status" label="已关闭" width="100" align="center">
    <template #default="scope">
      <el-tag :type="scope.row.status === 11 ? 'danger' : 'success'" size="small">
        {{ scope.row.status === 11 ? '是' : '否' }}
      </el-tag>
    </template>
  </el-table-column>
  </el-table>

  <!-- 分页及操作按钮 -->
  <div class="dialog-footer">
     <!-- 分页组件 -->
     <div class="pagination-wrapper">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="totalItems"
                :page-size="PopupsPageSize"
                :current-page="PopupsPageNo"
                @current-change="handlePageChange"
            />
        </div>
    <div class="action-buttons">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="confirmSelection">确定</el-button>
    </div>
  </div>
</el-dialog>


</template>



<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import type {FunctionalComponent} from 'vue'
import type {Column, InputInstance} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import type { SalesQuotation } from '@/types/public-xs/salesDocuments';
import type { SalesOrder } from '@/types/public-xs/salesDocuments';
import type { Goods } from '@/types/public-xs/Goods';
import type { SalesQuotationDetail } from '@/types/public-xs/salesDocuments';
import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { SalesOrderDetail } from '@/types/public-xs/salesDocuments';
 import type { User,Department } from '@/types/rs/User';
import request from '@/util/request';


//销售订单
let docCode=ref('')
//报价源单
let sourceSheet=ref('')
let title=ref('销售订单')
let goodsList=ref<Goods[]>([])
let pageNo=ref(1)
let pageSize=ref(5)
let allPage=ref(0)
let router=useRouter()
let route=useRoute()
//部门情况
const departments = ref([
  { value: 1, label: '销售部' },
  { value: 2, label: '技术部' },
  { value: 3, label: '财务部' }
])
//商品查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})


//填写信息区域的表单验证
const rules = reactive<FormRules>({
  cid: [
    { required: true, message: '必须选择客户', trigger: ['blur', 'change'] },
    { type: 'number', message: '需要数值类型' }
  ],
  docDate: [
    { required: true, message: '必须选择单据日期', trigger: 'change' },
    { validator: (_, value, callback) => {
        if (value > new Date()) return callback(new Error('不能选择未来日期'))
        callback()
      }
    }
  ],
  uid: [
    { required: true, message: '必须选择业务员', trigger: 'blur' }
  ],
  did: [
    { required: true, message: '必须选择部门', trigger: 'change' }
  ]
})
const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}

// 修改handleAction方法
const handleAction = (action:string) => {
  switch(action) {
    case 'choose':
      if (!salesOrders.value.cid) {
        ElMessage.warning('请先选择客户')
        return
      }
      dialogVisible.value = true
     searchSalesQuotes()  // 自动触发数据加载
      break
    case 'save-add':
      insertSalesOrder()
      break;
    case 'history':
      router.push('/home/SalesOrderInfo')
      break;



  }
}
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', pageSize.value.toString());
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);

    let response = await request.post('/basic/good/getAll', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    goodsList.value = response.data.data.map((item: any) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      unique: item.uname,
      tax: item.tax,
      stock: item.stock,
      kname: item.kname
    }));
    console.log(goodsList.value)
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    tableData.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}
fetchData(1)




const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'save-add',
    label: '保存新增',
    disabled: false
  },
  {
    name: 'audit',
    label: '审核',
    hidden: false
  },
  {
    name: 'choose',
    label: '选择源单',
    hidden: false
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }
])
let salesOrders=ref<SalesOrder>({
    id:0,
    docCode:docCode.value,
    docDate:new Date,
    cid: null,
    uid: 1,
    did:1,
    status: 0,
    totalQuantity: 100,
    totalAmount: 100,
    totalTaxValue: 100,
    notes: '',
    createBy: '毕建峰',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime: new Date,
    isDelete: 0,
    insStatus: 0,
    sourceSheet:sourceSheet.value,
    typeId:2,
    arBalance:0
})





//动态加载客户
let customerList=ref<Customer[]>([])
let selectCustomer=async()=>{
  let response=await request.post('/basic/Customer/selectAllCustomer')
  customerList.value=response.data.data
  console.log(customerList.value)

}
selectCustomer()

//查询业务员的方法
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()


//获取相应客户的报价单

let salesQuotesList=ref<SalesQuotation[]>([])


const loadData = async () => {
  try {
    // 1. 加载主数据
    const mainRes = await request.post(`/xs/salesOrder/selectSalesOrdersByCode?docCode=${route.params.docCode}`)
    salesOrders.value = mainRes.data.data
    
    // 2. 加载明细数据
    const detailRes = await request.post(`/xs/salesOrder/selectSalesOrdersDetailByCode?xsOrderCode=${route.params.docCode}`)
    console.log("全新明细数据",detailRes.data.data)
     // 3. 提取所有商品ID
    const goodIds = detailRes.data.data
      .map((item: any) => item.goodId)
      .filter((id: number) => id > 0);
    // 4. 批量查询商品信息
    const goodsRes = await request.post('/basic/good/getGoodList', goodIds 
    );
    
    console.log("信息是否完全",goodsRes)
    // 5. 创建商品映射表
    const goodsMap = new Map();
    goodsRes.data.data.forEach((good: Goods) => {
      goodsMap.set(good.id, good);
    });

    // 6. 合并数据到表格
    tableData.value = detailRes.data.data.map((item: any) => {
      const good = goodsMap.get(item.goodId) || {};
      return {
        code: good.code || '未知编码',
        goodsName: good.name || '未知商品',
        quantity: item.quantity,
        actualPrice: item.actualPrice,
        unit: good.uname || '件',
        stock: good.stock || 1000,
        goodId: item.goodId, // 保留原始ID用于后续操作
        tax:good.tax,
        kname:good.kname
      };
    });
    await selectCustomer()
    await fetchData(1)
    tableData.value.forEach(row => calculateTaxPrice(row))
    tableData.value = [...tableData.value] 
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

loadData()



// todo
const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}


const tableData = ref([{
    id: generateUUID(),
    goodId: 0,
    code: '',
    name: '',
    quantity: 1,
    actualPrice: 0,
    tax: 13,
    taxIncludedPrice: 0,
    stock: 100,
    unit: '件',
    kname: '测试',
    taxAmount: 0,
    taxTotal: 0

}])


//选中商品数据
const handleGoodsChange = (row:any) => {
  const selected = goodsList.value.find(item => item.code === row.code)
  if (selected) {
    row.goodsName = selected.name
    row.code=selected.code
    row.goodId = selected.id;
    row.stock = selected.stock;
    row.unit = selected.unique
    row.tax = selected.tax;
    row.kname = selected.kname
    row.stock=Math.max(1, selected.stock || 1)
    calculateTaxPrice(row)
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
    row.stock = 1
  }
    watch(() => [row.quantity, row.actualPrice], () => {
        calculateTaxPrice(row)
    }, { immediate: true })



}
const newSelectedRows = ref<any[]>([])

// 处理选中行变化
const newHHandleSelectionChange = (selection: any[]) => {
  newSelectedRows.value = selection
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
  if (newSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // 通过ID过滤实现删除
    const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
    tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}


//价格校验
const validatePrice = (row:any) => {
  row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
}

// 修改含税价计算方法
const calculateTaxPrice = (row: any) => {
    try {
        const unitPrice = Number(row.actualPrice) || 0
        const taxRate = (Number(row.tax) || 0) / 100
        const quantity = Number(row.quantity) || 0

        // 计算中间结果（保留4位小数）
        const unitTax = Number((unitPrice * taxRate).toFixed(4))
        row.taxAmount = Number((unitTax * quantity).toFixed(2))

        // 含税单价计算（四舍五入保留2位）
        row.taxIncludedPrice = Number((unitPrice + unitTax).toFixed(2))

        // 价税合计计算（四舍五入保留2位）
        row.taxTotal = Number((row.taxIncludedPrice * quantity).toFixed(2))
    } catch (e) {
        console.error('计算错误:', e)
        row.taxAmount = 0
        row.taxTotal = 0
    }
}

// 新增总税额计算属性
const totalTax = computed(() => {
    return tableData.value.reduce((sum, row) => {
        return sum + (Number(row.taxAmount) || 0)
    }, 0)
})

// 观察总税额变化
watch(totalTax, (newVal) => {
    salesOrders.value.totalTaxValue = Number(newVal.toFixed(2))
})
//只读队列
const readonlyColumns = [
  { prop: 'kname', label: '商品种类', width: 120 },
  { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
  { prop: 'tax', label: '增值税税率 (%)', width: 150 }
]

//格式化金额显示
const totalAmount = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (Number(row.taxTotal) || 0) // 直接累加每行的价税合计值
  }, 0)
})
const formatTotal = computed(() => {
  return `¥${totalAmount.value.toFixed(2)}`
})


//弹窗的处理
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(8)
const selectedCount = ref(0)
const totalItems = ref(0)
const dialogVisible = ref(false)
const currentSelected = ref<SalesQuotation | null>(null)
const selectedRows = ref<SalesQuotation[]>([]) // 多选时使用
const searchForm = reactive({
  docCode: '',
  startDate: '',
  endDate: ''
})

// 表格选择处理
const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
  selectedCount.value = selection.length
  if (selection.length > 0) {
    currentSelected.value = selection[0]
  } else {
    currentSelected.value = null
  }
}



const clearSelection = () => {

}

//分页方法
let handlePageChange=(newPage:number)=>{
   PopupsPageNo.value = newPage;
  searchSalesQuotes();

}


// 分页查询方法
const searchSalesQuotes = async () => {
  try {
    const res = await request.post('/xs/xs/selectSaleQuotesByPage', {
      doCode:searchForm.docCode,
      startDate:searchForm.startDate,
      endDate: searchForm.endDate,
      pageNo: PopupsPageNo.value,
      pageSize: PopupsPageSize.value,
      cid:salesOrders.value.cid,
      status:3

    })
    salesQuotesList.value = res.data.data.list
    totalItems.value = res.data.data.total
  } catch (error) {
    console.error('查询失败:', error)
  }
}

const resetSearch = () => {
  searchForm.docCode = ''
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchSalesQuotes()
}



const confirmSelection = async() => {
  if (currentSelected.value) {
    sourceSheet.value = currentSelected.value.doCode
    ElMessage.success(`已选择源单：${currentSelected.value.doCode}`)

    //获取到源单相应的明细数据
    try{
    const detailRes = await request.post(`/xs/xs/insertSalesQuotesDetailByCode?bjCode=${currentSelected.value.doCode}`)
    console.log("全新明细数据",detailRes.data.data)
    const goodIds = detailRes.data.data
      .map((item: any) => item.goodId)
      .filter((id: number) => id > 0);
    // 4. 批量查询商品信息
    const goodsRes = await request.post('/basic/good/getGoodList',goodIds);

    // 5. 创建商品映射表
    const goodsMap = new Map();
    goodsRes.data.data.forEach((good: Goods) => {
      goodsMap.set(good.id, good);
    });

    // 6. 合并数据到表格
    tableData.value = detailRes.data.data.map((item: any) => {
      const good = goodsMap.get(item.goodId) || {};
      return {
        code: good.code || '未知编码',
        goodsName: good.name || '未知商品',
        quantity: item.quantity,
        actualPrice: item.actualPrice,
        unit: item.uname || '件',
        stock: good.stock || 1000,
        goodId: item.goodId, // 保留原始ID用于后续操作
        tax: item.tax || good.tax,
        kname: good.kname || item.kname || '-',  // 双重保障

      };
      
    });
    tableData.value.forEach(row => calculateTaxPrice(row))
    tableData.value = [...tableData.value] 
    await selectCustomer()
    await fetchData(1)
  }catch{
    ElMessage.error('数据加载失败')
  }finally{
    dialogVisible.value = false
  }
  }
}
const generateDetails = () => {
  return tableData.value.map(item => ({
    id: 0,
    xsOrderCode: salesOrders.value.docCode,
    goodId: item.goodId,
    quantity: item.quantity,
    discountRate: 0,
    notes: '第一次测试',
    createBy: '毕建锋',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime:new Date ,
    isDelete: 0,
    warehouseId: 1,
    shippedQuantity: 0,
    actualPrice: item.actualPrice,
  }))  as SalesOrderDetail[]
}

let addGoodsRow = () => {
  tableData.value.push({
    id:generateUUID(),
    goodId:0,
    code: '',
    name:'',     // 商品编码（必填）
    quantity: 1,        // 数量（必填，默认1）
    actualPrice: 0,  // 实际报价
    tax: 13,        // 增值税率
    taxIncludedPrice: 0,  // 含税单价
    stock:100,
    unit: '件',
    kname:'测试',
    taxAmount: 0,
    taxTotal: 0
  })
}

const totalQuantity = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (Number.isInteger(row.quantity) ? Math.max(0, row.quantity) : 0)
  }, 0)
})
const validateGoodsRows = () => {
  let isValid = true
  const errors: string[] = []

  tableData.value.forEach((row, index) => {
    if (!row.code) {
      errors.push(`第${index+1}行：必须选择商品编码`)
      isValid = false
    }
    if (row.quantity <= 0 || isNaN(row.quantity)) {
      errors.push(`第${index+1}行：数量必须大于0`)
      isValid = false
    }
    if (row.actualPrice <= 0) {
      errors.push(`第${index+1}行：报价必须大于0`)
      isValid = false
    }
  })

  if (!isValid) {
    ElMessage.error({
      message: `商品信息不完整：\n${errors.join('\n')}`,
      duration: 5000
    })
  }
  return isValid
}



const formRef = ref<FormInstance>()
//点击新增后新增销售订单
const insertSalesOrder = async () => {
  // 1. 表单基础校验
  const formEl = formRef.value
  if (!formEl) return

  try {
    // 基础表单校验
    const valid = await formEl.validate()
    if (!valid) return

    // 2. 商品信息校验
    if (tableData.value.length === 0) {
      ElMessage.warning('至少需要添加一个商品')
      return
    }

    if (!validateGoodsRows()) return

    // 3. 执行提交逻辑
    const details = generateDetails()
    salesOrders.value.totalQuantity = totalQuantity.value
    salesOrders.value.totalAmount = totalAmount.value

    const response = await request.post('/xs/salesOrder/updateSalesOrders', {
      salesOrders: salesOrders.value,
      details: details,
      docCode:salesOrders.value.docCode
    })

    if (response.data.code ==200) {
      ElMessage.success('新增成功')
      router.push('/home/salesOrderInfo')
    } else {
      ElMessage.error(response.data.msg || '新增失败')
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

</script>


<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}
.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.date-label {
  color: #606266;
  margin: 0 10px;
}

.date-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

.selected-info {
  margin: 12px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-info {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
}
/* 错误状态样式 */
:deep(.el-form-item.is-error) {
  .el-input__inner, .el-select__wrapper {
    box-shadow: 0 0 3px rgba(245,108,108,.3);
  }
}

/* 表格错误行高亮 */
.el-table__row.error-row {
  td {
    background-color: #fff3f3 !important;
    .cell { 
      color: #f56c6c;
      font-weight: 500;
    }
  }
}

/* 新增滚动容器样式 */
.goods-table-container {
    max-height: 400px;
    /* 可根据实际需求调整高度 */
    overflow-y: auto;
    margin-top: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

/* 调整表格样式 */
.goods-table {
    min-width: 1200px;
    /* 根据列宽总和设置最小宽度 */
    width: 100%;
}

/* 美化滚动条（可选） */
.goods-table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: #f5f5f5;
}

</style>
